package pay

import (
	"context"
	"github.com/gin-gonic/gin"
	"github.com/smartwalle/alipay/v3"
	"go.uber.org/zap"
	"mxshop_api/order_web/global"
	"mxshop_api/order_web/proto"
	"mxshop_api/order_web/utils"
	"net/http"
)

func Notify(ctx *gin.Context) {
	//支付宝回调通知
	client, err := alipay.New(global.WebConfig.Alipay.AppID, global.WebConfig.Alipay.PrivateKey, false)
	if err != nil {
		zap.S().Errorw("实例化支付宝失败")
		utils.ResJson(ctx, http.StatusInternalServerError, err.Error(), nil)
		return
	}
	err = client.LoadAliPayPublicKey(global.WebConfig.Alipay.AliPublicKey)
	if err != nil {
		zap.S().Errorw("加载支付宝的公钥失败")
		utils.ResJson(ctx, http.StatusInternalServerError, err.Error(), nil)
		return
	}

	notify, err := client.GetTradeNotification(ctx.Request) //这个会自动验证签名是否正确
	if err != nil {
		utils.ResJson(ctx, http.StatusInternalServerError, err.Error(), nil)
		return
	}
	zap.S().Debugf("notify", notify)
	_, err = global.RpcClient.UpdateOrderStatus(context.Background(), &proto.OrderStatus{
		OrderSn: notify.OutTradeNo, // 商户订单号，这个是我们自己生成的订单号
		Status:  string(notify.TradeStatus),
	})
	if err != nil {
		utils.ResJson(ctx, http.StatusInternalServerError, err.Error(), nil)
		return
	}
	ctx.String(http.StatusOK, "success")
}
